﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class FarmAgroIndicatorFormReport : Form
    {
        public FarmAgroIndicatorFormReport()
        {
            InitializeComponent();
        }

        int regID, avpID, fhID = -1, cultID = -1, year = DateTime.Now.Year;

        private void FarmAgroIndicatorFormReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbCulture.SelectedIndexChanged -= cbCulture_SelectedIndexChanged;
            cbCulture.DataSource = UtilClass.GetCBCultureDataSourse();
            cbCulture.DisplayMember = "Name";
            cbCulture.ValueMember = "ID";
            cbCulture.SelectedIndex = -1;
            cbCulture.SelectedIndexChanged += new EventHandler(cbCulture_SelectedIndexChanged);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbFH.DataSource = null;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);

            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                cbFH.SelectedIndexChanged -= cbFH_SelectedIndexChanged;
                cbFH.Enabled = true;
                cbFH.DataSource = DBClass.Farms
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new { ID = se.ID, Name = se.Name })
                    .OrderBy(o => o.Name)
                    .ToArray();
                cbFH.DisplayMember = "Name";
                cbFH.ValueMember = "ID";
                cbFH.SelectedIndex = -1;
                cbFH.Text = string.Empty;
                cbFH.SelectedIndexChanged += new EventHandler(cbFH_SelectedIndexChanged);
            }
        }

        private void cbFH_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbFH.SelectedIndex >= 0)
            {
                fhID = Convert.ToInt32(cbFH.SelectedValue);
            }
            else
                fhID = 0;
        }


        private void cbCulture_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbCulture.SelectedIndex >= 0)
            {
                cultID = Convert.ToInt32(cbCulture.SelectedValue);
            }
            else
                cultID = 0;
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbYear.SelectedIndex >= 0)
            {
                year = Convert.ToInt32(cbYear.Items[cbYear.SelectedIndex].ToString());
            }
            else
                year = DateTime.Now.Year;
        }

        private void chbPFSH_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxPFSH.Enabled = chbFH.Checked;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
        }

        private void chbCulture_CheckedChanged(object sender, EventArgs e)
        {
            cbCulture.Enabled = chbCulture.Checked;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(DBClass.ConStr);
            SqlCommand com = new SqlCommand("FarmAgroIndicatorReport", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.Add("@Lang", SqlDbType.Bit).Value = InformationClass.Lang;
            com.Parameters.Add("@FarmID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@CultureID", SqlDbType.Int).IsNullable = true;
            com.Parameters.Add("@Year", SqlDbType.Int).IsNullable = true;

            if (chbFH.Checked && fhID > 0)
                com.Parameters["@FarmID"].Value = fhID;
            else
                com.Parameters["@FarmID"].Value = DBNull.Value;

            if (chbCulture.Checked && cultID > 0)
                com.Parameters["@CultureID"].Value = cultID;
            else
                com.Parameters["@CultureID"].Value = DBNull.Value;

            if (chbYear.Checked && year >= 1991)
                com.Parameters["@Year"].Value = year;
            else
                com.Parameters["@Year"].Value = DBNull.Value;

            System.Data.DataTable tab = new System.Data.DataTable("Rep");
            SqlDataAdapter adapter = new SqlDataAdapter(com);
            try
            {
                adapter.Fill(tab);
                dgvFarmAgroInd.DataSource = tab;

                if (InformationClass.Lang)
                {
                    dgvFarmAgroInd.Columns["AgroYear"].HeaderText = "Год";
                    dgvFarmAgroInd.Columns["AgroIndicator"].HeaderText = "Индикатор";
                }
                else
                {
                    dgvFarmAgroInd.Columns["AgroYear"].HeaderText = "Йил";
                    dgvFarmAgroInd.Columns["AgroIndicator"].HeaderText = "Индикатор";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(msgClass.msgNoData, msgClass.msgAchtung);
                dgvFarmAgroInd.DataSource = null;
            }
        }

        private void dgvFarmAgroInd_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex.Equals(dgvFarmAgroInd.Columns["AgroIndicator"].Index) && e.Value != null)
            {
                switch (e.Value.ToString())
                {
                    case "SeedQuantity":
                        e.Value = InformationClass.Lang ? "Семена (кг/га)" : "Уруғ (кг/га)";
                        break;
                    case "SeedCost":
                        e.Value = InformationClass.Lang ? "Семена (сум/га)" : "Уруғ (сўм/га)";
                        break;
                    case "FertilizerQuantity":
                        e.Value = InformationClass.Lang ? "Удобрения (кг/га)" : "Ўғит (кг/га)";
                        break;
                    case "FertilizerCost":
                        e.Value = InformationClass.Lang ? "Удобрения (сум/га)" : "Ўғит (сўм/га)";
                        break;
                    case "PesticideQuantity":
                        e.Value = InformationClass.Lang ? "Средства защиты (кг/га)" : "Кимёвий химоя, заҳарли химикатлар (кг/га)";
                        break;
                    case "PesticideCost":
                        e.Value = InformationClass.Lang ? "Средства защиты (сум/га)" : "Кимёвий химоя, заҳарли химикатлар (сўм/га)";
                        break;
                    case "MechWorkQuantity":
                        e.Value = InformationClass.Lang ? "Механ. труд (маш.час/га)" : "Механизациялашган меҳнат (маш.соат/га)";
                        break;
                    case "MechWorkCost":
                        e.Value = InformationClass.Lang ? "Механ. труд (сум/га)" : "Механизациялашган меҳнат (сўм/га)";
                        break;
                    case "HandWorkQuantity":
                        e.Value = InformationClass.Lang ? "Ручной труд (чел.дней/га)" : "Қўл меҳнати (киши кун/га)";
                        break;
                    case "HandWorkCost":
                        e.Value = InformationClass.Lang ? "Ручной труд (сум/га)" : "Қўл меҳнати (сўм/га)";
                        break;
                    case "TransportQuantity":
                        e.Value = InformationClass.Lang ? "Транспортные расходы" : "Транспорт ҳаражатлари";
                        break;
                    case "TransportCost":
                        e.Value = InformationClass.Lang ? "Транспортные расходы (сум/га)" : "Транспорт ҳаражатлари (сум/га)";
                        break;
                    case "WaterQuantity":
                        e.Value = InformationClass.Lang ? "Вода или затраты по доставке воды (м3/га)" : "Сув ёки сув етказиб бериш ҳаражатлари (м3/га)";
                        break;
                    case "WaterCost":
                        e.Value = InformationClass.Lang ? "Вода или затраты по доставке воды (сум/га)" : "Сув ёки сув етказиб бериш ҳаражатлари (сўм/га)";
                        break;
                    case "AgroProductionCost":
                        e.Value = InformationClass.Lang ? "Общие затраты на с/х производство (сум/га)" : "Қ/х ишлаб чиқариши учун умумий ҳаражатлар (сўм/га)";
                        break;
                    case "HarvestQuantity":
                        e.Value = InformationClass.Lang ? "Урожай (тонн/га)" : "Ҳосил (тонн/га)";
                        break;
                    case "HarvestCost":
                        e.Value = InformationClass.Lang ? "Стоимость урожая (сум/га)" : "Ҳосил қиймати (сўм/га)";
                        break;
                    case "FullProfit":
                        e.Value = InformationClass.Lang ? "Общая прибыль (сум/га)" : "Умумий даромад (сўм/га)";
                        break;
                    case "Tax":
                        e.Value = InformationClass.Lang ? "Налоги и др. расходы (сум/га)" : "Солиқлар ва бошқа ҳаражатлар (сўм/га)";
                        break;
                    case "ClearProfit":
                        e.Value = InformationClass.Lang ? "Чистая прибыль (сум/га)" : "Соф фойда (сўм/га)";
                        break;
                    case "WaterProductivity":
                        e.Value = InformationClass.Lang ? "Продуктивность воды (кг/м3)" : "Сув унумдорлиги (кг/м3)";
                        break;
                }
            }

            string[] cultures = InformationClass.Lang ? DBClass.Cultures.Select(se => se.Name).Distinct().ToArray() : DBClass.Cultures.Select(se => se.NameUz).Distinct().ToArray();

            if ((cultures.Contains(dgvFarmAgroInd.Columns[e.ColumnIndex].Name)) && e.Value != null)
            {
                e.Value = ((decimal)e.Value).ToString("N2");
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvFarmAgroInd.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelapp.Visible = true;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();
            excelapp.SheetsInNewWorkbook = 1;

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i26r21.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i26r21uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 

            int numPage = 1, left = 5, top = 11;

            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbFH.Checked)
            {
                excelworksheet.Cells[4, 3] = cbRegion.Text;
                excelworksheet.Cells[5, 3] = cbAVP.Text;
                excelworksheet.Cells[6, 3] = cbFH.Text;
            }
            if (chbYear.Checked)
                excelworksheet.Cells[7, 3] = cbYear.Text;


            for (int i = 2; i < dgvFarmAgroInd.ColumnCount; i++)
            {
                excelworksheet.Cells[10, i + 3] = dgvFarmAgroInd.Columns[i].HeaderText;
                addBorder(excelworksheet.Cells[10, i + 3]);

                for (int j = 0; j < dgvFarmAgroInd.RowCount; j++)
                {
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("SeedQuantity"))
                    {
                        excelworksheet.Cells[11, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[11, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("SeedCost"))
                    {
                        excelworksheet.Cells[12, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[12, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("FertilizerQuantity"))
                    {
                        excelworksheet.Cells[13, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[13, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("FertilizerCost"))
                    {
                        excelworksheet.Cells[14, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[14, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("PesticideQuantity"))
                    {
                        excelworksheet.Cells[15, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[15, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("PesticideCost"))
                    {
                        excelworksheet.Cells[16, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[16, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("MechWorkQuantity"))
                    {
                        excelworksheet.Cells[17, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[17, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("MechWorkCost"))
                    {
                        excelworksheet.Cells[18, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[18, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("HandWorkQuantity"))
                    {
                        excelworksheet.Cells[19, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[19, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("HandWorkCost"))
                    {
                        excelworksheet.Cells[20, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[20, 3 + i]);
                        continue;
                    }

                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("TransportCost"))
                    {
                        excelworksheet.Cells[21, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[21, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("WaterQuantity"))
                    {
                        excelworksheet.Cells[22, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[22, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("WaterCost"))
                    {
                        excelworksheet.Cells[23, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[23, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("AgroProductionCost"))
                    {
                        excelworksheet.Cells[24, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[24, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("HarvestQuantity"))
                    {
                        excelworksheet.Cells[25, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[25, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("HarvestCost"))
                    {
                        excelworksheet.Cells[26, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[26, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("FullProfit"))
                    {
                        excelworksheet.Cells[27, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[27, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("Tax"))
                    {
                        excelworksheet.Cells[28, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[28, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("ClearProfit"))
                    {
                        excelworksheet.Cells[29, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[29, 3 + i]);
                        continue;
                    }
                    if (dgvFarmAgroInd[1, j].Value.ToString().Equals("WaterProductivity"))
                    {
                        excelworksheet.Cells[30, 3 + i] = dgvFarmAgroInd[i, j].Value;
                        addBorder(excelworksheet.Cells[30, 3 + i]);
                        continue;
                    }
                }
            }

            excelworksheet.Columns.AutoFit();
            excelworksheet.Select(1);
        }

        string[] cultureNames = InformationClass.Lang ? DBClass.Cultures.Select(se => se.Name).Distinct().ToArray() : DBClass.Cultures.Select(se => se.Name).Distinct().ToArray();

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvFarmAgroInd.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvFarmAgroInd);
        }


    }
}
